package com.softmarket.filter;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.seasar.framework.util.ResourceUtil;

import com.softmarket.dto.DownloadPasswordDto;
import com.softmarket.service.DownloadPasswordService;

public class DownloadFilter implements Filter {

	public DownloadFilter() {
	}

	public void init(FilterConfig config) throws ServletException {
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String auth = req.getHeader("Authorization");
		if (!isAllowUser(auth)) {
			res.setHeader("WWW-Authenticate", "BASIC");
			res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//			res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
			return;
		}
		chain.doFilter(request, response);
		return;
	}

	private boolean isAllowUser(String auth) {
		if (auth == null) {
			return false;
		}

		if (!auth.toUpperCase().startsWith("BASIC ")) {
			return false;
		}

		String realm = auth.substring(6);

		try {
			String userpassDecoded = new String(new sun.misc.BASE64Decoder()
					.decodeBuffer(realm));

			String inputUsername = userpassDecoded.substring(0, userpassDecoded
					.indexOf(':'));
			String inputPasswd = userpassDecoded.substring(userpassDecoded
					.indexOf(':') + 1);

			DownloadPasswordService service = new DownloadPasswordService();
			DownloadPasswordDto dto = new DownloadPasswordDto();
			dto.setOrderNo(inputUsername);

			List<DownloadPasswordDto> resultList = service.select(dto);

			if (resultList.size() > 0) {
				DownloadPasswordDto last = resultList
						.get(resultList.size() - 1);
				long pass = new Date().getTime()
						- last.getCreateTime().getTime();
				String limitSetting = ResourceUtil.getProperties(
						"softmarket.properties").getProperty(
						"system.download.limit");
				long limit = Integer.parseInt(limitSetting) * 24 * 3600 * 1000;
				if (last.getDownloadKey().equals(inputPasswd) && pass < limit) {
					return true;
				}

			}
			return false;

		} catch (IOException e) {
			return false;
		} catch (IndexOutOfBoundsException e) {
			return false;
		}
	}
}